<template>
    <div class="profile-container">
        <el-card class="profile-card">
            <template #header>
                <div class="card-header">
                    <span>个人信息</span>
                </div>
            </template>

            <div class="profile-header">
                <div class="avatar-container">
                    <img :src="riderAvatar" alt="头像" class="avatar" v-if="userInfo && userInfo.name" />
                    <div class="avatar-placeholder" v-else>
                        <span class="initials">?</span>
                    </div>
                    <div class="name-badge">
                        <span class="name">{{ userInfo.name || '未登录' }}</span>
                        <el-badge :type="getStateType(userInfo.state)" class="state-badge">
                            {{ userInfo.state || '未知' }}
                        </el-badge>
                    </div>
                </div>
            </div>

            <el-descriptions
                v-if="userInfo && Object.keys(userInfo).length > 0"
                direction="vertical"
                :column="2"
                border
                class="profile-descriptions"
            >
                <el-descriptions-item label="骑手ID">{{ userInfo.id }}</el-descriptions-item>
                <el-descriptions-item label="认证状态">
                    <span :class="['state-tag', getStateClass(userInfo.state)]">{{ userInfo.state || '未知' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="骑手姓名">{{ userInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userInfo.phone }}</el-descriptions-item>
                <el-descriptions-item label="工作状态">{{ userInfo.gzzt }}</el-descriptions-item>
                <el-descriptions-item label="工作收入">{{ userInfo.gzsr }}</el-descriptions-item>
                <el-descriptions-item label="评分">{{ userInfo.mark }}</el-descriptions-item>
            </el-descriptions>

            <div v-else class="empty-state">
                <el-empty description="加载中..." />
            </div>

            <div class="action-buttons">
                <el-button type="primary" @click="showEditDialog" class="edit-button">编辑信息</el-button>
            </div>
        </el-card>

        <!-- 统计信息卡片 -->
        <div class="stats-container">
            <el-card class="stat-card">
                <div class="stat-wrapper">
                    <div class="stat-item">
                        <div class="stat-value">{{ stats.completedOrders }}</div>
                        <div class="stat-label">已完成订单</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">{{ stats.rating }}</div>
                        <div class="stat-label">满意度评分</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">{{ stats.onTimeRate }}%</div>
                        <div class="stat-label">准时率</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">{{ stats.completionRate }}%</div>
                        <div class="stat-label">完成率</div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 近期订单 -->
        <el-card class="recent-orders-card">
            <template #header>
                <div class="card-header">
                    <span>近期订单</span>
                    <el-button type="text" size="small" class="view-all-btn">查看全部</el-button>
                </div>
            </template>

            <el-table :data="recentOrders" border class="orders-table">
                <el-table-column prop="rider_name" label="骑手" width="100" />
                <el-table-column prop="dingdan_num" label="订单编号" width="150" />
                <el-table-column prop="name" label="用户名" width="110" />
                <el-table-column prop="address" label="配送地址" width="200" />
                <el-table-column prop="gratuity" label="配送费" width="80" />
                <el-table-column prop="end_time" label="配送时间" width="190" />
            </el-table>

            <div v-if="recentOrders.length === 0" class="empty-orders">
                <el-empty description="暂无订单记录" />
            </div>
        </el-card>
    </div>

    <!-- 编辑信息对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑个人信息" width="50%">
        <el-form :model="editForm" ref="editFormRef" label-position="right" label-width="100px">
            <el-form-item label="骑手姓名" prop="name">
                <el-input v-model="editForm.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="editForm.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="工作状态" prop="gzzt">
                <el-select v-model="editForm.gzzt" placeholder="请选择工作状态">
                    <el-option label="空闲" value="空闲" />
                    <el-option label="忙碌" value="忙碌" />
                    <el-option label="休息" value="休息" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleEdit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { ElMessage, FormInstance, ElBadge } from 'element-plus';

// 导入骑手头像
import riderAvatar from '../../assets/rider.jpg';

// 创建axios实例
const instance = axios.create({
    baseURL: '/api',
    timeout: 5000
});

// 请求拦截器
instance.interceptors.request.use(
    config => {
        // 检查是否有token
        const token = localStorage.getItem('riderToken') || sessionStorage.getItem('riderToken');
        if (token) {
            // 设置请求头
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器 - 处理 401 未授权
instance.interceptors.response.use(response => {
    return response
}, error => {
    if (error.response?.status === 401) {
        localStorage.removeItem('riderToken')
        sessionStorage.removeItem('riderToken')
        window.location.href = '/rider/login'
    }
    return Promise.reject(error)
})

// 根据认证状态获取标签类型
const getStateType = (state: string) => {
    switch (state) {
        case '已认证':
            return 'success';
        case '待认证':
            return 'warning';
        case '认证失败':
            return 'danger';
        default:
            return 'info';
    }
};

// 根据认证状态获取样式类
const getStateClass = (state: string) => {
    switch (state) {
        case '已认证':
            return 'state-success';
        case '待认证':
            return 'state-warning';
        case '认证失败':
            return 'state-danger';
        default:
            return 'state-info';
    }
};

const userInfo = ref({});
const stats = ref({
    completedOrders: 0,
    rating: 0,
    onTimeRate: 0,
    completionRate: 0
});

const recentOrders = ref([]);

// 获取统计数据
const fetchStatsData = async () => {
    try {
        const riderId = localStorage.getItem('riderId') || sessionStorage.getItem('riderId');
        if (!riderId) {
            throw new Error('骑手ID不存在');
        }
        const { data } = await instance.get(`/rider/stats`);
        stats.value = data || {
            completedOrders: 0,
            rating: 5,
            onTimeRate: 99,
            completionRate: 99
        }
    } catch (error) {
        console.error('获取统计数据失败:', error);
        ElMessage.error('获取统计数据失败');
    }
};

// 获取近期订单
const fetchRecentOrders = async () => {
    try {
        const riderId = localStorage.getItem('riderId') || sessionStorage.getItem('riderId');
        if (!riderId) {
            throw new Error('骑手ID不存在');
        }

        const { data } = await instance.get(`/dingdan?riderId=${riderId}`);

        console.log('订单数据:', data); // 调试用，查看返回结构

        // 确保 data 和 data.list 存在
        if (!data || !Array.isArray(data.list)) {
            ElMessage.warning('订单数据格式不正确');
            recentOrders.value = [];
            return;
        }

        // 获取当前骑手姓名
        const riderName = userInfo.value.name;
        if (!riderName) {
            throw new Error('当前骑手姓名不存在');
        }

        // 过滤属于当前骑手的订单
        const filteredOrders = data.list.filter(order => order.rider_name === riderName);

        // 计算已完成订单数（state === '5'）
        const completedOrders = filteredOrders.filter(order => order.state === '5').length;

        // 更新 stats
        stats.value.completedOrders = completedOrders;

        // 更新订单列表
        recentOrders.value = filteredOrders;

        // 计算总收入：sum(gratuity)
        const totalIncome = filteredOrders.reduce((sum, order) => {
            const gratuity = parseFloat(order.gratuity) || 0;
            return sum + gratuity;
        }, 0);

        // 更新用户信息中的 gzsr（工作收入）
        userInfo.value.gzsr = totalIncome.toFixed(2); // 保留两位小数

    } catch (error) {
        console.error('获取订单数据失败:', error);
        ElMessage.error('订单数据加载失败');
    }
};


// 查看全部订单
const viewAllOrders = () => {
    // 这里可以添加跳转到订单列表页的逻辑
    ElMessage.info('跳转到全部订单页面');
};
const editDialogVisible = ref(false);
const editFormRef = ref<FormInstance>();
const editForm = ref({});

// 获取用户信息
const fetchUserInfo = async () => {
    try {
        const riderId = localStorage.getItem('riderId') || sessionStorage.getItem('riderId');
        if (!riderId) {
            throw new Error('骑手ID不存在，请重新登录');
        }
        const { data } = await instance.get(`/rider/${riderId}`);
        // 假设后端返回格式为 { data: { ...userInfo } }
        userInfo.value = data.data || data;

    } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败，请重新登录');
    }
};

// 显示编辑对话框
const showEditDialog = () => {
    // 初始化编辑表单
    editForm.value = { ...userInfo.value };
    editDialogVisible.value = true;
};

// 处理编辑提交
const handleEdit = async () => {
    try {
        const { data } = await instance.put("/rider", editForm.value);

        if (data > 0) {
            ElMessage.success('更新成功');
            editDialogVisible.value = false;
            // 刷新用户信息
            fetchUserInfo();
        } else {
            ElMessage.error('更新失败');
        }
    } catch (error) {
        console.error('更新个人信息失败:', error);
        ElMessage.error('更新个人信息失败');
    }
};

// 组件挂载时获取用户信息
onMounted(() => {
    fetchUserInfo();
    fetchStatsData();
    fetchRecentOrders();
});
</script>

<style scoped>
.profile-container {
    max-width: 800px;
    margin: 30px auto;
    padding: 0 20px;
}

.profile-card {
    margin-bottom: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

.profile-card:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.profile-header {
    display: flex;
    align-items: center;
    padding: 20px 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 20px;
}

.avatar-container {
    display: flex;
    align-items: center;
}

.avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #f0f0f0;
}

.avatar-placeholder {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 32px;
    color: #909399;
    border: 3px solid #f0f0f0;
}

.initials {
    font-weight: bold;
}

.name-badge {
    margin-left: 20px;
}

.name {
    font-size: 20px;
    font-weight: bold;
    color: #303133;
    display: block;
    margin-bottom: 5px;
}

.state-badge {
    margin-top: 5px;
}

.profile-descriptions {
    margin-bottom: 20px;
}

.el-descriptions__label {
    font-weight: bold;
    color: #606266;
}

.state-tag {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.state-success {
    background-color: #f0f9eb;
    color: #67c23a;
}

.state-warning {
    background-color: #fdf6ec;
    color: #e6a23c;
}

.state-danger {
    background-color: #fef0f0;
    color: #f56c6c;
}

.state-info {
    background-color: #edf2fc;
    color: #909399;
}

.empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
    background-color: #fafafa;
    border-radius: 8px;
}

.action-buttons {
    display: flex;
    justify-content: flex-end;
    padding-top: 20px;
}

.edit-button {
    transition: all 0.3s ease;
}

.edit-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式调整 */
@media (max-width: 768px) {
    .profile-container {
        padding: 0 15px;
    }

    .profile-header {
        flex-direction: column;
        text-align: center;
    }

    .avatar-container {
        flex-direction: column;
    }

    .name-badge {
        margin-left: 0;
        margin-top: 15px;
    }

    .el-descriptions {
        column-count: 1 !important;
    }

    .action-buttons {
        justify-content: center;
    }
}
.stats-container {
    margin-top: 20px;
    margin-bottom: 20px;
    overflow-x: auto;
}

.stat-card {
    padding: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    width: 100%;
}

.stat-wrapper {
    display: flex !important;
    flex-direction: row !important;
    flex-wrap: nowrap !important;
    justify-content: space-between !important;
    width: 100%;
    min-width: 600px;
}

.stat-card:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.12);
}

.stat-item {
    flex: 0 0 auto !important;
    width: 25% !important;
    min-width: 120px !important;
    text-align: center;
    padding: 10px;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #1890ff;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 14px;
    color: #606266;
}

.recent-orders-card {
    margin-top: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

.recent-orders-card:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.12);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.view-all-btn {
    color: #1890ff;
}

.orders-table {
    margin-top: 10px;
}

.order-status-success {
    color: #67c23a;
    padding: 2px 8px;
    border-radius: 4px;
    background-color: #f0f9eb;
}

.order-status-warning {
    color: #e6a23c;
    padding: 2px 8px;
    border-radius: 4px;
    background-color: #fdf6ec;
}

.order-status-danger {
    color: #f56c6c;
    padding: 2px 8px;
    border-radius: 4px;
    background-color: #fef0f0;
}

.order-status-info {
    color: #909399;
    padding: 2px 8px;
    border-radius: 4px;
    background-color: #f4f4f5;
}

.empty-orders {
    padding: 30px 0;
    text-align: center;
}

@media (max-width: 768px) {
    .stat-item {
        min-width: 50%;
    }

    .orders-table {
        font-size: 12px;
    }

    .el-table-column {
        padding: 0 5px;
    }
}
</style>
